/**
 *
 * Copyright 2012 TeleNav, Inc. All rights reserved.
 * SkyActivity.java
 * @author jwmeng (jwmeng@telenavsoftware.com)
 * @date 2012-10-17
 */
package com.telenav.module.user;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;
import com.telenav.app.HomeActivity;
import com.telenav.app.R;
import com.telenav.comm.HostProvider;
import com.telenav.common.ui.CustomDialog;
import com.telenav.data.dao.DaoManager;
import com.telenav.gcm.GcmProxy;
import com.telenav.xmpp.XmppTool;

public class LoginActivity extends Activity {
	
	private TextView okBtn;
	private TextView registerBtn;
	private TextView name;
	private TextView pwd;
	private Dialog myDialog;
	private int mCount = 0;
	private final String  servletName = "LoginServlet";
	private static final int ITEM1 = Menu.FIRST;
	private static final int ITEM2 = Menu.FIRST + 1;
	private AsyncTask<Void, Void, Void> mRegisterTask;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_login);
        
        okBtn = (TextView)this.findViewById(R.id.btn_login);
        registerBtn = (TextView)this.findViewById(R.id.btn_login_register);
        name = (TextView)this.findViewById(R.id.input_username); 
        pwd = (TextView)this.findViewById(R.id.input_pwd);
        
        okBtn.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0) 
			{
				login();
			}
        });
        registerBtn.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View paramView) 
			{
				Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
				startActivity(intent);
			}
        	
        });
    }
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	menu.add(0,ITEM1,0,"Login");
    	menu.add(0,ITEM2,0,"Exit");
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    	case ITEM1:
    		login(name.getText().toString(),pwd.getText().toString());
    		break;
    	case ITEM2:
    		finish();
    		break;
    	}
    	return true;
    }
    
    private void login()
    {
	       mCount = 0;
	       CustomDialog localMyProgressDialog = new CustomDialog(this);
	       myDialog = localMyProgressDialog;
           myDialog.show();
           login(name.getText().toString(),pwd.getText().toString());
           myDialog.cancel();
    }
    
    private void login(String username, String password)
    {
    	try {
    		XmppTool.getConnection().login(username, password);
    		
			Presence presence = new Presence(Presence.Type.available);
			XmppTool.getConnection().sendPacket(presence);
			DaoManager.getInstance().getAccountDao().setAccount(username, password);
			if(!DaoManager.getInstance().getAccountDao().isRegister())
			{
				cloud();
				DaoManager.getInstance().getAccountDao().setIsRegister(true);
			}
			Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
			startActivity(intent);
		} catch (XMPPException e) {
			XmppTool.closeConnection();
			DaoManager.getInstance().getAccountDao().setAccount(null, null);
			Toast.makeText(LoginActivity.this, "login failure", 0).show();
		}
    }
    
    public void cloud()
    {
        checkNotNull(HostProvider.APP_URL, "SERVER_URL");
        checkNotNull(HostProvider.SENDER_ID, "SENDER_ID");
        // Make sure the device has the proper dependencies.
        GCMRegistrar.checkDevice(this);
        // Make sure the manifest was properly set - comment out this line
        // while developing the app, then uncomment it when it's ready.
        GCMRegistrar.checkManifest(this);

        final String regId = GCMRegistrar.getRegistrationId(this);
        if (regId.equals("")) 
        {
            // Automatically registers application on startup.
            GCMRegistrar.register(this, HostProvider.SENDER_ID);
        }
        else
        {
            // Device is already registered on GCM, check server.
            if (GCMRegistrar.isRegisteredOnServer(this)) 
            {
                // Skips registration.
                Log.i(this.getClass().getName(), getString(R.string.already_registered) + "\n");
            } else {
                // Try to register again, but not in the UI thread.
                // It's also necessary to cancel the thread onDestroy(),
                // hence the use of AsyncTask instead of a raw thread.
                final Context context = this;
                mRegisterTask = new AsyncTask<Void, Void, Void>() {

                    @Override
                    protected Void doInBackground(Void... params) {
                        boolean registered = GcmProxy.register(context, regId);
                        // At this point all attempts to register with the app
                        // server failed, so we need to unregister the device
                        // from GCM - the app will try to register again when
                        // it is restarted. Note that GCM will send an
                        // unregistered callback upon completion, but
                        // GCMIntentService.onUnregistered() will ignore it.
                        if (!registered) {
                            GCMRegistrar.unregister(context);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        mRegisterTask = null;
                    }

                };
                mRegisterTask.execute(null, null, null);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mRegisterTask != null) {
            mRegisterTask.cancel(true);
        }
        GCMRegistrar.onDestroy(this);
        super.onDestroy();
    }

    private void checkNotNull(Object reference, String name) {
        if (reference == null) {
            throw new NullPointerException(
                    getString(R.string.error_config, name));
        }
    }
}